//项目权属管理
import * as React from 'react';
import {
  Table,
  Form,
  Select,
  Input,
  Button,
  Col,
  Row,
  Modal,
  Checkbox,
  notification,
  DatePicker,
  Spin,
  message
} from 'antd';
import axios from 'axios';
import Api from '../../services/apis';
import moment from 'moment';

import Link from 'umi/link';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './style.less';

const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;
const RangePicker = DatePicker.RangePicker;
@connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))

class EnergyCostMaintenance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      sTransferUnit: [],//划转单位下拉
      sCommunitiesByTrUnit: [],//小区信息
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
      "transfer_unit": "",//划转单位名称
      "community_name": "",//小区名称
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
      "fee_type": "",//费用类型
      "begin_time": "",//开始时间
      "end_time": "",//终止时间
      "currentPage": 1,//当前页
      "pageSize": 10,//页大小
      feeType: [],
      tableData: [],
      loading: false,
      current: 1,
      totalSize: 0,
      m_current: 1,
      m_pageSize: 5,
      submitFlag: '',
      rooms: [],
      cabinets: [],
      boxs: [],
      modalLoading: false,
      bags: [],
      keyId: '',
      searchData: {
        transfer_unit: '',
        community_name: '',
        building_code: '',
        house_code: '',
        begin_time: '',
        end_time: '',
        fee_type: '',
        currentPage: 1,
        pageSize: 10,
      },
      modalTitle: '',
      feeDate: '',
      statisticDate: '',
      statisticType: [],
      nowItem: ''
    };
  }
  changeDate(type, dates, dateStrings) {
    switch (type) {
      case 'search':
        this.setState({
          "begin_time": dateStrings[0],//开始时间
          "end_time": dateStrings[1],//终止时间
        });
        break;
      case 'feeDate':
        this.setState({
          feeDate: dateStrings
        });
        break;
      case 'statisticDate':
        this.setState({
          statisticDate: dateStrings
        });
        break;

      default:
        this.setState({
          "begin_time": dateStrings[0],//开始时间
          "end_time": dateStrings[1],//终止时间
        });
        break;
    }
  }

  componentWillMount() {
    this.getAllTransferUnit();
    this.getAllFeeType();
    this.getAllStatisticType();
    this.getTableData(this.state.searchData);
  }

  modalSubmit() {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let param = {
        };
        for (let key in values) {
          param[key.slice(2)] = values[key];
        };
        param.pay_fee_date = values.m_feeDate ? moment(values.m_feeDate).format('YYYY-MM-DD') : '';
        param.statisticDate = values.m_feeDate ? moment(values.m_statisticDate).format('YYYY-MM-DD') : '';
        param.building_code = param.building_name;
        param.house_code = param.house_name;
        console.log(param);

        this.maintainData(param);
      }
    })
  }
  setModalVisible(modalVisible, modalType, nowItem) {
    //this.resetForm();
    let modalTitle = '';
    switch (modalType) {
      case 'new':
        modalTitle = '新建费用维护';
        break;
      default:
        modalTitle = '编辑费用维护';
        break;
    };
    this.setState({ modalVisible, modalType, modalTitle, nowItem });
  }

  resetForm() {
    this.props.form.resetFields();
    const searchData = {
      transfer_unit: '',
      community_name: '',
      building_code: '',
      house_code: '',
      begin_time: '',
      end_time: '',
      fee_type: '',
      currentPage: 1,
      pageSize: 10,
    };
    this.setState({ searchData });
    this.getTableData(searchData);
  }

  query = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      let data = { ...values };
      data.begin_time = Array.isArray(values.date) ? moment(values.date[0]).format('YYYY-MM-DD') : '';
      data.end_time = Array.isArray(values.date) ? moment(values.date[1]).format('YYYY-MM-DD') : '';
      data.currentPage = this.state.currentPage;
      data.pageSize = this.state.pageSize;
      this.setState({
        searchData: data
      });
      this.getTableData(data);
    });
  }

  getTableData(data) {
    this.setState({
      loading: true
    });
    axios.post(Api.getFeeMaintainList, data).then((res) => {
      let tableData = res.data.data.feeMaintainList;
      if (Number(res.data.code) !== 0) {
        message.error('查询失败');
        this.setState({
          loading: false
        });
        return false;
      };
      for (let i = 0, len = tableData.length; i < len; i++) {
        tableData[i].key = i;
      };
      this.setState({
        tableData,
        loading: false,
        totalSize: res.data.data.count
      });
    });
  }

  pageChange = (page) => {
    this.setState({ current: page }, () => {
      let data = this.state.searchData;
      data.currentPage = page;
      this.getTableData(data);
    })
  }


  getAllTransferUnit() {
    axios.get(Api.getAllTransferUnit).then((res) => {
      this.setState({
        sTransferUnit: res.data.data
      });
    });
  }

  changeTransferUnit(index, val) {
    this.getCommunitiesByTrUnit(val.props.children);
    this.setState({
      sCommunitiesByTrUnit: [],//小区信息
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "community_name": "",//小区名称
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_community_name": "",//小区名称
        "m_building_code": "",//楼栋代号
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }
  maintainData(data) {
    this.setState({
      modalLoading: true
    });
    const type = this.state.modalType;
    const nowItem = this.state.nowItem;
    switch (type) {
      case 'new':
        axios.post(Api.addOrUpdateFeeMaintain, data).then((res) => {
          if (Number(res.data.code) !== 0) {
            message.error(`新建失败，${res.data.data}`);
          } else {
            message.success(res.data.data);
            this.setModalVisible(false);
            this.getTableData(this.state.searchData);
          };
          this.setState({
            modalLoading: false
          });
        });
        break;

      case 'updata':
        axios.post(Api.addOrUpdateFeeMaintain, { id: nowItem.id, ...data }).then((res) => {
          if (Number(res.data.code) !== 0) {
            message.error(`更新失败，${res.data.data}`);
          } else {
            message.success(res.data.data);
            this.setModalVisible(false);
            this.getTableData(this.state.searchData);
          };
          this.setState({
            modalLoading: false
          });
        });
        break;
    }

  }
  changeCommunitiesByTrUnit(index, item) {

    this.getBuildsByProjCode(this.state.sCommunitiesByTrUnit[item.key].projectCode);
    this.setState({
      sBuildsByProjCode: [],//栋号
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "building_code": "",//楼栋代号
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_building_code": "",//楼栋代号
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }
  changeBuildsByProjCode(index, item) {
    this.getAllHousesByBuildingCode(this.state.sBuildsByProjCode[item.key].buildingCode);
    this.setState({
      sHousesByBuildingCode: [],//房号
    });
    let reset = {
      "house_code": "",//户代号
    };;
    if (this.state.modalVisible) {
      reset = {
        "m_house_code": "",//户代号
      };
    }
    this.props.form.setFieldsValue(reset);
  }

  getCommunitiesByTrUnit(transfer_unit) {
    axios.post(Api.getCommunitiesByTrUnit, { transfer_unit }).then((res) => {
      this.setState({
        sCommunitiesByTrUnit: res.data.data
      });
    });
  }

  getBuildsByProjCode(project_code) {
    axios.post(Api.getBuildsByProjCode, { project_code }).then((res) => {
      this.setState({
        sBuildsByProjCode: res.data.data
      });
    });
  }
  getAllHousesByBuildingCode(building_code) {
    axios.post(Api.getAllHousesByBuildingCode, { building_code }).then((res) => {
      this.setState({
        sHousesByBuildingCode: res.data.data
      });
    });
  }

  getAllFeeType() {
    axios.get(Api.getAllFeeType).then((res) => {
      this.setState({
        feeType: res.data.data
      });
    });
  }

  getAllStatisticType() {
    axios.get(Api.getAllStatisticType).then((res) => {
      this.setState({
        statisticType: res.data.data
      });
    });
  }
  deleteFeeMaintain(item) {
    Modal.warning({
      title: '确认删除本条数据？',
      content: [<p>注意，删除后不可恢复。</p>, <p>esc关闭此窗口。</p>],
      okText: '确认删除',
      onOk: () => {
        axios.post(Api.deleteFeeMaintain, { id: item.id }).then((res) => {
          if (Number(res.data.code) !== 0) {
            message.error(res.data.data);
          } else {
            message.success(res.data.data);
            this.getTableData(this.state.searchData);
          };
        });
      }
    });
  }
  render() {
    const that = this;
    const { getFieldDecorator } = this.props.form;
    const {
      currentUserLoading,
    } = this.props;

    const columns = [
      {
        title: '划转单位',
        dataIndex: 'transfer_unit',
        key: 'transfer_unit',
      },
      {
        title: '小区名称',
        dataIndex: 'community_name',
        key: 'community_name'
      },
      {
        title: '楼栋名称',
        dataIndex: 'building_name',
        key: 'building_name',
      },
      {
        title: '户名',
        dataIndex: 'house_name',
        key: 'house_name',
      },
      {
        title: '费用类型',
        dataIndex: 'fee_type',
        key: 'fee_type',
      },
      {
        title: '租户承担费用',
        dataIndex: 'tenant_fee',
        key: 'tenant_fee',
      },
      {
        title: '单价',
        dataIndex: 'unit_price',
        key: 'unit_price',
      },
      {
        title: '总价',
        dataIndex: 'total_price',
        key: 'total_price',
      },
      {
        title: '缴费日期',
        dataIndex: 'pay_fee_date',
        key: 'pay_fee_date',
        render: (text) => (
          moment(text).format('YYYY-MM-DD')
        )
      },
      {
        title: '说明',
        dataIndex: 'description',
        key: 'description',
      },
      {
        title: '操作',
        key: 'action',
        render: (item, record) => (
          <span>
            <Link target='_blank' to={{
              pathname: '/fe/dataMaintenance/energyDetails',
              search: `?id=${item.id}`
            }}>
              <Button type='primary'>详情</Button>
            </Link>
            &emsp;
              <Button type='primary' onClick={this.setModalVisible.bind(this, true, 'updata', item)}>编辑</Button>
            &emsp;
            <Button type='primary' onClick={this.deleteFeeMaintain.bind(this, item)}>删除</Button>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>能耗费用维护</p>
              <p>ENERGY COST MAINTENANCE</p>
            </div>
          </div>
          <div className="pom">
            <div className='mrb15'>
              <Form layout='inline' align='left' onSubmit={this.query.bind(this)}>
                <FormItem label="划转单位：">
                  {
                    getFieldDecorator('transfer_unit')(
                      <Select
                        placeholder="请选择划转单位"
                        onChange={this.changeTransferUnit.bind(this)}
                      >
                        {this.state.sTransferUnit.map((item, index) => (
                          <Option value={item} key={index}>{item}</Option>
                        ))}
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem label='小区信息：'>
                  {
                    getFieldDecorator('community_name')(
                      <Select
                        placeholder="请选择小区信息"
                        onChange={this.changeCommunitiesByTrUnit.bind(this)}
                      >
                        {this.state.sCommunitiesByTrUnit.map((item, index) => (
                          <Option value={item.address} key={index}>{item.address}</Option>
                        ))}
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem label='栋号：'>
                  {
                    getFieldDecorator('building_code')(
                      <Select
                        placeholder="请选择栋号"
                        onChange={this.changeBuildsByProjCode.bind(this)}
                      >
                        {this.state.sBuildsByProjCode.map((item, index) => (
                          <Option value={item.buildingCode} key={index}>{item.buildingName2}</Option>
                        ))}
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem label='房号：'>
                  {
                    getFieldDecorator('house_code')(
                      <Select
                        placeholder="请选择房号"
                      >
                        {this.state.sHousesByBuildingCode.map((item, index) => (
                          <Option value={item.houseCode} key={index}>{item.houseName2}</Option>
                        ))}
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem label='费用类型：'>
                  {
                    getFieldDecorator('fee_type')(
                      <Select placeholder="请选择费用类型：">
                        {this.state.feeType.map((item, index) => (
                          <Option value={item.dicName} key={index}>{item.dicName}</Option>
                        ))}
                      </Select>
                    )
                  }
                </FormItem>
                <FormItem
                  label='缴费时间：'
                  className={styles.rangePicker}
                >
                  {
                    getFieldDecorator('date')(
                      <RangePicker
                        ranges={{ '今天': [moment(), moment()], '本月': [moment().startOf('month'), moment().endOf('month')] }}
                        onChange={this.changeDate.bind(this, 'search')}
                      />)
                  }
                </FormItem>

                <Row gutter={24} style={{ textAlign: 'center' }}>
                  <Button icon='search' type='primary' htmlType='submit'>搜索</Button>
                  &emsp;
                  <Button icon="plus-circle" type="primary" htmlType='button' onClick={this.setModalVisible.bind(this, true, 'new')}>新建</Button>
                  &emsp;
                  <Button icon="reload" type="primary" htmlType='button' onClick={this.resetForm.bind(this)}>重置</Button>
                </Row>
              </Form>
            </div>
            <Spin spinning={this.state.loading}>
              <Table
                bordered={true}
                scroll={{ x: true }}
                columns={columns}
                dataSource={that.state.tableData}
                pagination={{
                  current: that.state.current,
                  onChange: this.pageChange.bind(this),
                  total: that.state.totalSize,
                  showTotal: total => `共 ${total} 项`
                }} />
            </Spin>
          </div>
          <Modal
            title={this.state.modalTitle}
            destroyOnClose={true}
            centered
            visible={this.state.modalVisible}
            width={830}
            className='modalAlign'
            onCancel={this.setModalVisible.bind(this, false)}
            footer={[
              <Button key="back" onClick={this.setModalVisible.bind(this, false)}>取消</Button>,
              <Button key="submit" type="primary" loading={this.state.modalLoading} onClick={this.modalSubmit.bind(this)}>
                提交
              </Button>,
            ]}
          >
            <Form layout='inline' align='left' onSubmit={this.query.bind(this)}>
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="划转单位：">
                    {
                      getFieldDecorator('m_transfer_unit', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.transfer_unit : '',
                        rules: [{ required: true, message: '请选划转拨单位!' }],
                      })(
                        <Select
                          placeholder="请选择划转单位"
                          onChange={this.changeTransferUnit.bind(this)}
                        >
                          {this.state.sTransferUnit.map((item, index) => (
                            <Option value={item} key={index}>{item}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='小区信息：'>
                    {
                      getFieldDecorator('m_community_name', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.community_name : '',
                      })(
                        <Select
                          placeholder="请选择小区信息"
                          onChange={this.changeCommunitiesByTrUnit.bind(this)}
                        >
                          {this.state.sCommunitiesByTrUnit.map((item, index) => (
                            <Option value={item.address} key={index}>{item.address}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='楼栋名称：'>
                    {
                      getFieldDecorator('m_building_name', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.building_name : '',
                      })(
                        <Select
                          placeholder="请选择楼栋名称"
                          onChange={this.changeBuildsByProjCode.bind(this)}
                        >
                          {this.state.sBuildsByProjCode.map((item, index) => (
                            <Option value={item.buildingCode} key={index}>{item.buildingName2}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='户名：'>
                    {
                      getFieldDecorator('m_house_name', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.house_name : '',
                      })(
                        <Select
                          placeholder="请选择户名"
                        >
                          {this.state.sHousesByBuildingCode.map((item, index) => (
                            <Option value={item.houseCode} key={index}>{item.houseName2}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='费用类型：'>
                    {
                      getFieldDecorator('m_fee_type', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.fee_type : '',
                        rules: [{ required: true, message: '请选择费用类型!' }],
                      })(
                        <Select placeholder="请选择费用类型">
                          {this.state.feeType.map((item, index) => (
                            <Option value={item.dicName} key={index}>{item.dicName}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='统计形式：'>
                    {
                      getFieldDecorator('m_statistic_type', {
                        initialValue: this.state.modalType === 'updata' ? this.state.nowItem.statistic_type : '',
                        rules: [{ required: true, message: '请选择统计形式!' }],
                      })(
                        <Select placeholder="请选择统计形式">
                          {this.state.statisticType.map((item, index) => (
                            <Option value={item.dicName} key={index}>{item.dicName}</Option>
                          ))}
                        </Select>
                      )
                    }
                  </FormItem>
                </Col>
                <Col
                  span={8}

                >
                  <FormItem
                    label='缴费时间：'
                  >{getFieldDecorator('m_feeDate', {

                    initialValue: this.state.modalType === 'updata' && this.state.nowItem.pay_fee_date ? moment(this.state.nowItem.pay_fee_date) : '',
                    rules: [{ required: true, message: '请输入缴费时间!' }],
                  })(
                    <DatePicker
                      ranges={{ '今天': [moment(), moment()], '本月': [moment().startOf('month'), moment().endOf('month')] }}
                      onChange={this.changeDate.bind(this, 'feeDate')}
                    />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='特殊情况说明：'>
                    {getFieldDecorator('m_description', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.description : '',
                    })(<Input placeholder="请输入特殊情况说明" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='租户承担费用：'>
                    {getFieldDecorator('m_tenant_fee', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.tenant_fee : '',
                    })(<Input placeholder="请输入租户承担费用" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='单价：'>
                    {getFieldDecorator('m_unit_price', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.unit_price : '',
                      rules: [{ required: true, message: '请输入单价!' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }],
                    })(<Input placeholder="请输入单价" />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='总价：'>
                    {getFieldDecorator('m_total_price', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.total_price : '',
                      rules: [{ required: true, message: '请输入总价!' }, { pattern: /^[0-9]+([.]{1}[0-9]+){0,1}$/, message: '请输入数值！' }],
                    })(<Input placeholder="请输入总价" />)}
                  </FormItem>
                </Col>
                <Col
                  span={8}
                >
                  <FormItem label='统计日期：'>

                    {getFieldDecorator('m_statisticDate', {
                      initialValue: this.state.modalType === 'updata' && this.state.nowItem.statisticDate ? moment(this.state.nowItem.statisticDate) : '',
                      rules: [{ required: true, message: '请输入统计日期!' }],
                    })(
                      <DatePicker
                        ranges={{ '今天': [moment(), moment()], '本月': [moment().startOf('month'), moment().endOf('month')] }}
                        onChange={this.changeDate.bind(this, 'statisticDate')}
                      />)}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem label='表数量：'>
                    {getFieldDecorator('m_display_number', {
                      initialValue: this.state.modalType === 'updata' ? this.state.nowItem.display_number : '',
                    })(<Input placeholder="请输入表数量" />)}
                  </FormItem>
                </Col>
              </Row>
            </Form>
          </Modal>
        </div>
      </PageHeaderWrapper>
    );
  }
}

const WrappedApp = Form.create()(EnergyCostMaintenance);

export default WrappedApp;
